﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HZ.MBSM.Model;
using HZ.MBSM.DBUtility;
using System.Text;

public partial class Bidder_BidPrice1 : System.Web.UI.Page
{
    Int32 prjid;
    bool bPrint = false;
    String BP1strConditions;
    public String BP1Status;
    string bidprice1pwd, bidprice1rond;
    Int64 BidPrice1Accountid_TBR;
    private const int GridColumnIndexOfSPPrice = 10;
    private const int GridColumnIndexOfPriceSwitching = 12;

    protected void Page_Load(object sender, EventArgs e)
    {

        System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> _AccountType = new System.Collections.Generic.List<HZ.MBSM.DAL.AccountType>();
        _AccountType.Add(HZ.MBSM.DAL.AccountType.enumCompany);
        if (HZ.MBSM.BLL.Login.CheckAssert(_AccountType))
        {
            //if (Config.EnableEncrypt && !HZ.Encrypt.EncryptWrapper.SetKey)
            //{
            //    HZ.Web.MessageBox.Show("密钥尚未加载无法报价");
            //}


            prjid = Int32.Parse(SysFun.IsSQL(Request.QueryString["projectid"]));//项目id

            Db db = new Db();
            if (Session["Pass"] == null || Session["Pass"].ToString() != "OK")
            {
                Response.Write("<script>window.alert('报价密码不正确！！');</script>");
                Response.Write("<script>window.location=\"Nothing.aspx?Projectid=" + prjid.ToString() + "\"</script>");
                return;
            }

            #region 提交报价


            if (Request.Form["SavePrice"] == "提交本页报价")
            {
                ErrorMsg.Text = "";
                System.Text.StringBuilder smPrice = new System.Text.StringBuilder("");
                System.Text.StringBuilder spPrice = new System.Text.StringBuilder("");
                System.Text.StringBuilder bidID = new System.Text.StringBuilder("");
                System.Text.StringBuilder sqlbatchcmd = new StringBuilder();
                foreach (GridViewRow row in GridView1.Rows)
                {
                    if (row.RowType == DataControlRowType.DataRow)
                    {

                        string a = Request.Form["txtprice" + row.Cells[0].Text.Trim()];
                        if (!SysFun.IsNumeric(a.Trim()))//判断输入的是否是数值
                        {
                            ErrorMsg.Text += row.Cells[1].Text + "报价只能为数字<br>";
                            Response.Write("<script>window.alert('报价只能为数字！')</script>");
                        }
                        else
                        {

                            a = Convert.ToDecimal(a.Trim()).ToString("F2");
                            //判断当前输入得值是否越界,
                            if (Convert.ToDecimal(a) < 0 || Convert.ToDecimal(a) > 99999999)
                            {
                                ErrorMsg.Text += row.Cells[1].Text + "报价数有误<br>";
                                Response.Write("<script>window.alert('报价数有误！')</script>");
                            }
                            else
                            {
                                if (SysFun.ToDec(row.Cells[7].Text) <= Convert.ToDecimal(a))
                                {
                                    ErrorMsg.Text += row.Cells[1].Text + "报价不能大于限价<br>";
                                    Response.Write("<script>window.alert('报价数有误！')</script>");
                                    break;
                                }
                               
                                if (Config.EnableEncrypt)
                                {
                                    sqlbatchcmd.AppendFormat("UPDATE Project_Bid SET EncryptedPrice = '{0}', SPPrice = NULL,SMPrice = NULL WHERE BidId = {1};", HZ.Encrypt.EncryptWrapper.EncrytPrice(Session["bidPassword"].ToString(), a), row.Cells[0].Text);
                                }
                                else
                                {
                                    //判断当前价格是否被修改过，如果没有修改，就不将此价格放到提交列表中
                                    if (a != row.Cells[GridColumnIndexOfSPPrice].Text.ToString())
                                    {
                                        //包装报价
                                        spPrice.Append(Convert.ToDecimal(a) + "$");
                                        string _strLimtPrice = Convert.ToDecimal(Convert.ToDecimal(a) / (Convert.ToDecimal(row.Cells[6].Text))).ToString("N4");
                                        //制剂报价
                                        smPrice.Append(Convert.ToDecimal(_strLimtPrice) + "$");
                                        bidID.Append(row.Cells[0].Text + "$");
                                    }
                                }
                            }
                        }
                    }

                    if (smPrice.ToString().Length > 0 || sqlbatchcmd.Length > 0)
                    {
                        if (Config.EnableEncrypt)
                        {
                            Db crydb = new Db();
                            try
                            {

                                db.Command(sqlbatchcmd.ToString(), 120);
                            }
                            catch
                            {

                                ErrorMsg.Text = "报价失败！重试";
                            }
                            finally
                            {
                                db.Close();
                            }
                        }
                        else
                        {

                            HZ.MBSM.BLL.CompanyBidding cmpBid = new HZ.MBSM.BLL.CompanyBidding();
                            if (cmpBid.BidPrice_QuotedPrice(smPrice.ToString(), spPrice.ToString(), bidID.ToString()))//执行存储过程
                            {
                                HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
                                HZ.MBSM.BLL.LogManage.RecordLoginDetail(_Account.AccountName, Request.UserHostAddress, "更新", "bidprice", "BidPrice_QuotedPrice", "../Bidder/BidPrice1.aspx");

                                ErrorMsg.Text += "本页报价成功，未报价做零处理";
                            }
                            else
                                ErrorMsg.Text += "报价失败！重试";
                        }
                    }


                }

            }
            #endregion


            showGridView();


        }
    }


    /// <summary>
    /// 查询总共有多少页
    /// </summary>
    /// <returns></returns>
    /// <summary>
    /// 将数据绑定到GridView1
    /// </summary>
    /// <param name="PageIndex">转向第几页</param>
    public void showGridView()
    {
        BP1strConditions = fctConditions();
        Db db = new Db();
        DbPage dbPage = new DbPage(db);
        dbPage.Table = "BidGoods_View";                                               //要查询的表明
        dbPage.Key = "Bidid";                                               //表的主键    
        dbPage.Where = BP1strConditions;                                           //查询条件


        if (Config.EnableEncrypt)
        {
            dbPage.SelectField = " bidid,Goodsid,productname,outlookc,Medicinemodel,factoryName,unit,factor,FactoryUserCode,Convert(Numeric(20,2),LimitPrice*convert(decimal(18,2),factor)) as LimitPricePack,Convert(Numeric(20,4),LimitPrice) as LimitPriceMin, EncryptedPrice , Smprice ,SPPrice,limitprice,PriceSwitching";//要显示的字段
        }
        else
        {
            dbPage.SelectField = " bidid,Goodsid,productname,outlookc,Medicinemodel,factoryName,unit,factor,FactoryUserCode,Convert(Numeric(20,2),LimitPrice*convert(decimal(18,2),factor)) as LimitPricePack,Convert(Numeric(20,4),LimitPrice) as LimitPriceMin, EncryptedPrice , Smprice ,SPPrice,limitprice,PriceSwitching";//要显示的字段
        }
        dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页   
        if (Request.Form["subPrint"] == "投标报价一览表" || Request.Form["subPrint"] == "预览并打印")
        {
            dbPage.PageSize = 1;                                                    //没有显示记录条数  
        }
        else
        {
            dbPage.PageSize = 10;                                                    //没有显示记录条数  

        }

        dbPage.OrderBy = "ProductName,Medicinemodel,Outlookc,Bidid";                  //排序字段
        System.Data.IDataReader dr = dbPage.ExecuteReader();
        GridView1.DataSource = dr;
        GridView1.DataBind();

        dr.Close();
        dr.Dispose();
        dbPage.Db.Close();
        db.Close();
        this.DbPageFlip1.DbPage = dbPage;//将数据传给控键
        if (Request.Form["subPrint"] == "投标报价一览表")
        {
            PrintTable();
        }

    }

    public string fctConditions()
    {
        string strtemp;
        string PN = SysFun.ToTrim(ProductName.Text);
        string BPGoodsid = txtGoodsId.Text.Trim();
        string ComSC = txtCompanySc.Text.Trim();

        HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
        if (_Account != null)
        {
            BidPrice1Accountid_TBR = SysFun.ToLong(_Account.AccountId);
            strtemp = " AccountID_TB='" + BidPrice1Accountid_TBR.ToString() + "' and CheckStatus='1' And ProjectId=" + prjid.ToString() + " And";
            if (PN != "")
            {
                strtemp += " productname like '%" + PN + "%' And";
            }
            if (BPGoodsid != "")
            {
                strtemp += " Goodsid ='" + BPGoodsid + "' And";
            }
            if (ComSC != "")
            {
                strtemp += " factoryName like '%" + ComSC + "%' And";
            }
            string _strMedicinemodel = txtMedicinemodel.Text.ToString();
            if (_strMedicinemodel != "")
            {
                strtemp += "  Medicinemodel like '%" + _strMedicinemodel + "%' And";
            }
            string _strUserCode_SC = txtUserCode_SC.Text.ToString();
            if (_strUserCode_SC != "")
            {
                strtemp += "  FactoryUserCode like '%" + _strUserCode_SC + "%' And";
            }
            string _strPriceState = lstPriceState.SelectedValue;
            switch (_strPriceState)
            {
                case "全部":
                    break;
                case "未报价":
                    strtemp += " ((spprice=0 or spprice is null) AND EncryptedPrice IS NULL) and";
                    break;
                case "已报价":
                    strtemp += " (spprice>0 OR EncryptedPrice IS NOT NULL) and";
                    break;
            }
            if (strtemp != "")
            {
                strtemp = "  " + strtemp.Substring(0, strtemp.Length - 3);
            }
        }
        else
        {
            strtemp = "";

        }
        return strtemp;


    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string bidprice = "";
            if (!string.IsNullOrEmpty(e.Row.Cells[13].Text) && e.Row.Cells[13].Text != "&nbsp;")
            {
                //HZ.Encrypt.EncryptWrapper.DecrytPrice
                bidprice = HZ.Encrypt.EncryptWrapper.DecrytPrice(Session["bidPassword"].ToString(), e.Row.Cells[14].Text);
                if (bidprice == "&nbsp;") bidprice = "";
                //int a = int.Parse(e.Row.Cells[6].Text);
                //float  spprice = float.Parse(bidprice) / a;
                //e.Row.Cells[9].Text = spprice.ToString();
                //edit by ws 去掉制剂报价
            }
            if (e.Row.Cells[GridColumnIndexOfPriceSwitching].Text == "0")//判断报价开关
            {
                e.Row.Cells[8].Text = bidprice;

                BP1Status = "none";

            }
            else
            {
                if (Request.Form["subPrint"] == "投标报价一览表")
                {
                    e.Row.Cells[8].Text = bidprice;
                }
                else
                {

                    e.Row.Cells[8].Text = "<input style='width: 60px' type=text name='txtprice" + e.Row.Cells[0].Text + "' value=\"" + bidprice + "\" /> ";


                }
                BP1Status = "block";
            }


        }
        e.Row.Cells[0].Visible = true;//不显示BIDID
        e.Row.Cells[GridColumnIndexOfSPPrice].Visible = false;//不显示最小包装价
        e.Row.Cells[GridColumnIndexOfPriceSwitching].Visible = false;//不显示PriceSwitching
        e.Row.Cells[14].Visible = false;//不显示 
        e.Row.Cells[11].Visible = false;
        // e.Row.Cells[11].Visible = false;


    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //OverRide　为了使导出成Excel可行！

    }

    private void PrintTable()
    {


        SysFun.WriteToExcel(GridView1, this.Page, "投标报价一览表.xls");



    }

}
